/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package anton.dinner;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;

/**
 *
 * @author johan
 */
@ManagedBean
@SessionScoped
public class DinnerHasIngredients {
    
   public Integer itemID;
   
   public String dinnerName;
     
     int i;
  
   @Resource(name="jdbc/antonsDatasource")
     
   private DataSource ds;
   
//------------------------------------------------------------------------------
//setter and getter methods
   public String getDinnerName() {
        return dinnerName;
    }

    public void setDinnerName(String dinnerName) {
        this.dinnerName = dinnerName;
    }

    public Integer getItemID() {
        return itemID;
    }

    public void setItemID(Integer itemID) {
        this.itemID = itemID;
    }
//------------------------------------------------------------------------------
    
      // method used to add entry to mysql database
    
      public  String add( ) throws SQLException {
       
       if (itemID!=0 & !dinnerName.equals("") ){
      
       if(ds==null)
			throw new SQLException("Can't get data source");// throws exception i database not available
 
		//database connection
		Connection con = ds.getConnection();
                
                
 
		if(con==null)
			throw new SQLException("Can't get database connection");
         try (PreparedStatement ps = con.prepareStatement(
                 "insert into DinnerIngredients (dinner_name,item_ID ) values (?,?)")) {
             
             ps.setString( 1, dinnerName );
             
             ps.setInt(2, itemID);
             
             i= ps.executeUpdate();
             
             
         }
       }
       
         return "newjsf"; 
     
        
    }   
    
}
